package web.myBook.controllers;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.myBook.slayer.model.MyBook;

@Component
public class BookValidator implements Validator {
	public boolean supports(Class<?> klass) {
		return MyBook.class.isAssignableFrom(klass);
	}

	public void validate(Object target, Errors errors) {
		MyBook book = (MyBook) target;
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "bookId",
				"validation.error.isEmpty");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "bookTitle",
				"validation.error.isEmpty");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "author",
				"validation.error.isEmpty");
		long id = book.getBookId();
		
		int idLength = Long.toString(id).length();
		System.out.println("Length og id is.........."+idLength);
		if (idLength > 50 || idLength < 1) {
			errors.rejectValue("bookId", "validation.error.isLength");
		}
		String bookTitle = book.getBookTitle();
		System.out.println("BookTitle og id is.........."+bookTitle.length());
		if (bookTitle.length() > 100 || bookTitle.length() < 2) {
			errors.rejectValue("bookTitle", "validation.error.isLength");
		}
		String author = book.getAuthor();
		System.out.println("author og id is.........."+author.length());
		if (author.length() > 100 || author.length() < 2) {
			errors.rejectValue("author", "validation.error.isLength");
		}
		
	}
}
